#!/usr/bin/env python
# -*- coding: utf-8 -*-
from my_app import db
from flask_wtf import FlaskForm
from wtforms import StringField, DecimalField, SelectField
from decimal import Decimal
from wtforms.validators import InputRequired, NumberRange, ValidationError
from flask_wtf.file import FileField, FileRequired


"""
注意事项：
1、Flask外键字段在创建对象赋值时，需要赋值对象，而不是该对象的id或者其他单独的字段
"""


#  创建数据库模型
class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))
    price = db.Column(db.Float)
    # 定义模型的外键，id表示为关系
    category_id = db.Column(db.Integer, db.ForeignKey("category.id"))
    image_path = db.Column(db.String(255))
    # backref 反向查询；在视图中编写类似 user.products时，即可访问user中的产品信息
    category = db.relationship("Category", backref=db.backref("products", lazy="dynamic"))
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
    user = db.relationship("User", backref=db.backref("products", lazy="dynamic"))

    def __init__(self, name, price, category, image_path, user):
        self.name = name
        self.price = price
        self.category = category
        self.image_path = image_path
        self.user = user

    def __repr__(self):
        return f"<Product {self.id}>"


class Category(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255))
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))
    user = db.relationship("User", backref=db.backref("categories", lazy="dynamic"))

    def __init__(self, name, user):
        self.name = name
        self.user = user

    def __repr__(self):
        return f"<Category {self.id}>"


# 创建表单
class NameForm(FlaskForm):
    """公共表单"""
    name = StringField('Name', validators=[InputRequired()])


class ProductForm(NameForm):
    price = DecimalField('Price', validators=[InputRequired(), NumberRange(min=Decimal(0.0))])
    category = SelectField('Category', validators=[InputRequired()], coerce=int)
    image = FileField('Product Image', validators=[FileRequired()])


def check_duplicate_category():
    """检查名称是否重复"""
    def _check_duplicate(form, field):
        res = Category.query.filter(Category.name == field.data).first()
        if res:
            raise ValidationError(f"分组 {field.data} 已存在！")
    return _check_duplicate


class CategoryForm(NameForm):
    name = StringField('Name', validators=[InputRequired(), check_duplicate_category()])

